$(function () {
    // $('input[type="file"]').prettyFile();
    var smnote = $(".summernote").summernote({
        lang: "zh-CN",
        onImageUpload: function (files, editor, $editable) {
            hotUtil.uploadImg(files, "goods", function (url, path) {
                editor.insertImage($editable, url);
            });
        }
    });
    $('.imgpreview').click(function () {
        $("#uploadfile").click();
    });
    $('body').delegate("#uploadfile", 'change', function () {
        hotUtil.loading.show();
        hotUtil.uploadImg($("#uploadfile")[0].files, "banner", function (url, path) {
            hotUtil.loading.close();
            $(".imgpreview").attr("src", url);
            $("#goodsPic").val(path);
            $("#goodsFullPic").val(url);
        });
    });

    jsHelper.init();
    $(".OnlyFloat").OnlyFloat();
    $(".OnlyNum").OnlyNum();

    // 添加新一行元素
    $(".add-pin-dot-config").on("click", function () {
        jsHelper.initPinDotRewardConfig(null);
    });
});

var jsHelper = {
    rewardConfig: {},
    params: {
        goodsId: hotUtil.getQuery("goodsId")
    },
    init: function () {
        var self = this;
        if (hotUtil.isNullOrEmpty(self.params.goodsId)) {
            self.params.goodsId = 0;
            return;
        }
        $(".pin-dot").html("");
        hotUtil.loading.show();
        hotUtil.ajaxCall("/goods/ajax/getgoodsinfo", self.params, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 2000 && ret.data != null) {
                $("#goodsName").val(ret.data.goodsName);
                $("#goodsBn").val(ret.data.goodsBn);
                $("#goodsPrice").val(ret.data.price);
                $("#wholesalePrice").val(ret.data.wholesalePrice);
                $("#quotaCount").val(ret.data.quota);
                $("#wholesaleNeedQuota").val(ret.data.wholesaleNeedQuota);
                $("#retailStore").val(ret.data.retailStore);
                $("#totalWholesaleStore").val(ret.data.totalWholesaleStore);
                $("#todayLimitBuy").val(ret.data.todayLimitBuy);
                $("#goodsPic").val(ret.data.pic);
                $("#goodsFullPic").val(ret.data.fullPic);
                $(".imgpreview").attr("src", ret.data.fullPic);
                self.setEditContent(ret.data.description);
                self.rewardConfig = ret.data.rewardConfig;
                if (
                    typeof self.rewardConfig != "undefined" &&
                    self.rewardConfig != null &&
                    self.rewardConfig.pinTeamRewardConfig != null
                ) {
                    $.each(self.rewardConfig.pinTeamRewardConfig, function (i, item) {
                        $("#invitePeopleCount" + (item.tier === 2 ? "2" : "")).val(
                            item.invitePeopleCount
                        );
                        $("#eachPenTakeReward" + (item.tier === 2 ? "2" : "")).val(
                            item.eachPenTakeReward
                        );
                    });
                }
            }
            if (
                typeof self.rewardConfig !== "undefined" &&
                self.rewardConfig !== null
            ) {
                self.initPinDotRewardConfig(self.rewardConfig.pinDotRewardConfig);
            }
        });
    },
    edit: function () {
        var self = this;
        if (hotUtil.isNullOrEmpty($("#goodsName").val())) {
            swal("请输入商品标题", "", "warning");
            $("#goodsName").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#goodsBn").val())) {
            swal("请输入商品编号", "", "warning");
            $("#goodsBn").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#goodsPrice").val())) {
            swal("请输入零售价", "", "warning");
            $("#goodsPrice").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#wholesalePrice").val())) {
            swal("请输入批发价格", "", "warning");
            $("#wholesalePrice").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#wholesalePrice").val())) {
            swal("请输入配送数量", "", "warning");
            $("#wholesalePrice").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#quotaCount").val())) {
            swal("请输入配送额度", "", "warning");
            $("#quotaCount").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#wholesaleNeedQuota").val())) {
            swal("请输入批发所需配额", "", "warning");
            $("#wholesaleNeedQuota").focus();
            return false;
        }
        if (hotUtil.isNullOrEmpty($("#totalWholesaleStore").val())) {
            swal("请输入批发库存", "", "warning");
            $("#totalWholesaleStore").focus();
            return false;
        }

        if (hotUtil.isNullOrEmpty($("#todayLimitBuy").val())) {
            swal("请输入限购数量", "", "warning");
            $("#todayLimitBuy").focus();
            return false;
        }
        var pinTeamRewardConfig = self.getPinTeamRewardConfig();
        if (pinTeamRewardConfig.length === 0) {
            swal("请完善相关配置", "", "warning");
            return false;
        }
        var result = self.getPinDotRewardConfig();
        if (!result.success) {
            return false;
        }
        var pinDotRewardConfig = result.pinDotRewardConfig;
        var param = {
            goodsId: self.params.goodsId,
            goodsName: $("#goodsName").val(),
            goodsBn: $("#goodsBn").val(),
            price: $("#goodsPrice").val(),
            quotaCount: $("#quotaCount").val(),
            wholesaleNeedQuota: $("#wholesaleNeedQuota").val(),
            wholesalePrice: $("#wholesalePrice").val(),
            totalWholesaleStore: $("#totalWholesaleStore").val(),
            pic: $("#goodsPic").val(),
            fullPic: $("#goodsFullPic").val(),
            todayLimitBuy: $("#todayLimitBuy").val(),
            pinTeamRewardConfigJson: JSON.stringify(pinTeamRewardConfig),
            pinDotRewardConfigJson: JSON.stringify(pinDotRewardConfig),
            description: hotUtil.encode(self.getEditContent())
        };
        hotUtil.loading.show();
        // if (!hotUtil.isNullOrEmpty($("#uploadfile").val())) {
        //     hotUtil.uploadImg($("#uploadfile")[0].files, "goods", function (url) {
        //         param.pic = url;
        //         $(".imgpreview").attr("src", url);
        //         self.submit(param);
        //     });
        // } else {
        //     self.submit(param);
        // }
        self.submit(param);
    },
    submit: function (param) {
        var self = this;
        hotUtil.ajaxCall("/goods/ajax/editgoods", param, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 2000) {
                self.params.goodsId = ret.data;
                swal("提交成功", "", "success");
            } else {
                swal("提交失败", "", "error");
            }
        });
    },

    getEditContent: function () {
        return $(".summernote").code();
    },
    setEditContent: function (content) {
        $(".summernote").code(content);
    },
    /**
     * 初始化拼点奖励
     * @param data 初始化地址
     */
    initPinDotRewardConfig: function (data) {
        var self = this;
        var template = $("#pin_dot_reward_config").html();
        var html = "";
        var len = $(".pin-dot").children(".col-sm-12").length;
        if (typeof data != "undefined" && data != null && data.length > 0) {
            len = data.length;
            $.each(data, function (i, item) {
                var tempHtml = template;
                tempHtml = tempHtml.replace(/{sort}/gm, item.sort);
                tempHtml = tempHtml.replace(/{finishPenCount}/gm, item.finishPenCount);
                tempHtml = tempHtml.replace(/{eachPenReward}/gm, item.eachPenReward);
                tempHtml = tempHtml.replace(
                    /{inviteMinPeopleCount}/gm,
                    item.inviteMinPeopleCount
                );
                tempHtml = tempHtml.replace(
                    /{minBranchPeopleCount}/gm,
                    item.minBranchPeopleCount
                );
                tempHtml = tempHtml.replace(/{flatLevelReward}/gm, item.flatLevelReward);
                html += tempHtml;
            });
        } else {
            len++;
            var tempHtml = template;
            tempHtml = tempHtml.replace(/{sort}/gm, len);
            tempHtml = tempHtml.replace(/{finishPenCount}/gm, 0);
            tempHtml = tempHtml.replace(/{eachPenReward}/gm, 0);
            tempHtml = tempHtml.replace(/{inviteMinPeopleCount}/gm, 0);
            tempHtml = tempHtml.replace(/{minBranchPeopleCount}/gm, 0);
            tempHtml = tempHtml.replace(/{flatLevelReward}/gm, 0);
            html = tempHtml;
        }
        $(".pin-dot").append(html);

        // 处理删除按钮

        if (len > 0) {
            $(".pin-remove").remove();
            var remove_tempate = $("#remove_tempate").html();
            remove_tempate = remove_tempate.replace(/{sort}/gm, len);
            $(".remove_" + len).html(remove_tempate);
        }
        // 绑定删除按钮事件
        self.removePinDotRewardRow();
    },
    /**
     * 获取拼团奖励
     */
    getPinTeamRewardConfig: function () {
        var config = [];
        for (var i = 1; i <= 2; i++) {
            var rewardConfig = {};
            rewardConfig.tier = i;
            rewardConfig.invitePeopleCount = 0;
            rewardConfig.eachPenTakeReward = 0;
            if (
                !hotUtil.isNullOrEmpty(
                    $("#invitePeopleCount" + (i === 2 ? "2" : "")).val()
                ) &&
                parseInt($("#invitePeopleCount" + (i === 2 ? "2" : "")).val()) >= 0
            ) {
                rewardConfig.invitePeopleCount = $(
                    "#invitePeopleCount" + (i === 2 ? "2" : "")
                ).val();
            }
            if (
                !hotUtil.isNullOrEmpty(
                    $("#eachPenTakeReward" + (i === 2 ? "2" : "")).val()
                ) &&
                parseFloat($("#eachPenTakeReward" + (i === 2 ? "2" : "")).val()) >= 0
            ) {
                rewardConfig.eachPenTakeReward = $(
                    "#eachPenTakeReward" + (i === 2 ? "2" : "")
                ).val();
            }
            config.push(rewardConfig);
        }
        return config;
    },
    /**
     * 获取拼点奖励配置
     */
    getPinDotRewardConfig: function () {
        var result = {
            success: true
        };
        var pinDotRewardConfig = [];
        var len = $(".pin-dot").children(".col-sm-12").length;
        for (var i = 1; i <= len; i++) {
            var config = {
                sort: i,
                finishPenCount: $("#finishPenCount_" + i).val(),
                eachPenReward: $("#eachPenReward_" + i).val(),
                inviteMinPeopleCount: $("#inviteMinPeopleCount_" + i).val(),
                minBranchPeopleCount: $("#minBranchPeopleCount_" + i).val(),
                flatLevelReward: $("#flatLevelReward_" + i).val()
            };
            if (
                hotUtil.isNullOrEmpty(config.finishPenCount) ||
                hotUtil.isNullOrEmpty(config.eachPenReward) ||
                hotUtil.isNullOrEmpty(config.inviteMinPeopleCount) ||
                hotUtil.isNullOrEmpty(config.minBranchPeopleCount) ||
                hotUtil.isNullOrEmpty(config.flatLevelReward) ||
                parseInt(config.finishPenCount) < 0 ||
                parseFloat(config.eachPenReward) < 0 ||
                parseInt(config.inviteMinPeopleCount) < 0 ||
                parseInt(config.minBranchPeopleCount) < 0 ||
                parseInt(config.flatLevelReward) < 0
            ) {
                swal("拼点奖励配置", "请完善拼点奖励相关配置", "warning");
                result.success = false;
                return false;
            }
            // 判断上一条配置是否存在，如果存在，则判断数据是否大于上一条
            if (pinDotRewardConfig.length > 0) {
                var _cfg = pinDotRewardConfig[i - 2];
                if (
                    parseInt(_cfg.finishPenCount) >= config.finishPenCount ||
                    parseFloat(_cfg.eachPenReward) >= parseFloat(config.eachPenReward) ||
                    parseInt(_cfg.inviteMinPeopleCount) >
                    parseInt(config.inviteMinPeopleCount) ||
                    parseInt(_cfg.minBranchPeopleCount) >
                    parseInt(config.minBranchPeopleCount)
                ) {
                    swal("", "阶梯奖品配置必须大于上一条配置");
                    result.success = false;
                    return false;
                }
            }
            pinDotRewardConfig.push(config);
        }
        result.pinDotRewardConfig = pinDotRewardConfig;
        return result;
    },
    removePinDotRewardRow: function () {
        var self = this;
        // 移除行元素
        $(".pin-remove")
            .off("click")
            .on("click", function () {
                var removeId = $(this).attr("data-id");
                $(".row_" + removeId).remove();
                if (removeId > 1) {
                    var remove_tempate = $("#remove_tempate").html();
                    remove_tempate = remove_tempate.replace(/{sort}/gm, removeId - 1);
                    $(".remove_" + (removeId - 1)).html(remove_tempate);
                    // 绑定删除按钮事件
                    self.removePinDotRewardRow();
                }
            });
    }
};
